<template>
  <div class="app-container">
    <el-row :gutter="10">
      <el-col :span="4">
        <el-card shadow="never">
          <div class="card-head">
            <el-tooltip content="切换用例库" placement="top-start">
              <svg-icon icon-class="caselib" class="clickable-icon" @click="changeSelect" />
            </el-tooltip>
            <el-tooltip v-if="!isChange" :content="curCaselibName" placement="top-start">
              <div class="card-head__text">
                <span class="text-content"># {{ curCaselibName }}</span>
              </div>
            </el-tooltip>
            <el-select v-if="isChange" v-model="curCaselibId" filterable placeholder="请选择" style="margin-left: 10px;" @change="selectChange">
              <el-option
                v-for="item in caselibOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                :disabled="item.id == curCaselibId"
              />
            </el-select>
          </div>
          <!-- 引入目录树组件 -->
          <CatalogTree :catalog-type="0" :related-id="curCaselibId" @throwCatalogList="receiveCatalogList" @changeCatalogId="changeCatalogId" />
        </el-card>
      </el-col>
      <el-col :span="20">
        <el-card shadow="never">
          <el-form :inline="true" style="float: right;">
            <el-form-item>
              <el-select v-model="level" placeholder="优先级" clearable @change="fetchData">
                <el-option
                  v-for="item in levelOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select v-model="status" placeholder="状态" clearable @change="fetchData">
                <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-input v-model="q" placeholder="请输入用例标题" clearable @keyup.enter.native="fetchData">
                <i slot="suffix" class="el-input__icon el-icon-search clickable" @click="fetchData" />
              </el-input>
            </el-form-item>
          </el-form>
          <el-form :inline="true">
            <el-form-item>
              <el-button type="primary" icon="el-icon-plus" @click="addCase">新增用例</el-button>
              <!-- <el-button icon="el-icon-link" @click="handleCreate">关联计划</el-button>
              <el-button icon="el-icon-rank" @click="handleCreate">批量移动</el-button>
              <el-button icon="el-icon-delete" @click="handleCreate">批量删除</el-button> -->
            </el-form-item>
            <el-form-item>
              <el-dropdown>
                <el-button> 更多操作<i class="el-icon-arrow-down el-icon--right" /></el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item
                    class="custom-dropdown-item"
                    icon="el-icon-delete"
                    :disabled="multipleSelection.length <= 0"
                    @click.native="handleBatchDelete"
                  >批量删除</el-dropdown-item>
                  <el-dropdown-item
                    class="custom-dropdown-item"
                    icon="el-icon-download"
                    @click.native="handleImport"
                  >导入用例</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-form-item>
          </el-form>
          <el-table
            v-loading="listLoading"
            :data="caseList"
            :header-cell-style="{ background: '#fafafa' }"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50" />
            <el-table-column prop="id" label="ID" width="100" />
            <el-table-column prop="title" label="用例标题" />
            <el-table-column prop="version.name" label="当前版本" width="100" />
            <el-table-column prop="max_version.name" label="最高版本" width="100" />
            <el-table-column prop="level" label="优先级" width="100">
              <template slot-scope="scope">
                <el-tag :effect="scope.row.level=='P0'?'dark':'light'" :type="scope.row.level=='P0'?'danger':scope.row.level=='P1'?'':'info'">{{ scope.row.level }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template slot-scope="scope">
                <el-tag :type="scope.row.status==1?'success':scope.row.status==0?'':'info'">{{ scope.row.status==1?'已完成':scope.row.status==0?'进行中':'已废弃' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="update_time" label="更新时间" width="150" />
            <el-table-column prop="update_user.name" label="更新人" width="100" />
            <el-table-column label="操作" align="center" fixed="right" width="200">
              <template slot-scope="scope">
                <el-button type="text" @click="editCase(scope.row)">编辑</el-button>
                <el-button type="text" @click="deleteCase(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <pagination v-show="total > 0" :total="total" :page.sync="page" :limit.sync="limit" @pagination="fetchData" />
        </el-card>
      </el-col>
    </el-row>

    <el-drawer :title="caseDrawerTitle" :visible.sync="caseDrawerShow" :wrapper-closable="false" size="60%">
      <Detail
        ref="caseDetail"
        :catalog-options="catalogOptions"
        :case-form="caseInfo"
        :steps="steps"
        :submit-type="submitType"
        @closeDrawer="closeDrawer"
        @getTestcaseInfo="getTestcaseInfo"
        @refreshList="fetchData"
      />
    </el-drawer>
    <el-drawer title="导入测试用例" :visible.sync="importDrawerShow">
      <Upload @down="downTemplateFile" />
    </el-drawer>
  </div>
</template>

<script>
import apiCaselib from '@/api/functional/caselib'
import apiTestcase from '@/api/functional/testcase'
import apiVer from '@/api/system/version'
import Pagination from '@/components/Pagination'
import CatalogTree from '@/components/CatalogTree'
import Upload from '@/components/Business/Upload.vue'
import Detail from './detail'
const defaultCaseInfo = {
  id: null,
  title: '',
  level: '',
  desc: '',
  status: null,
  precondition: '',
  version_id: '',
  caselib_id: '',
  catalog_id: ''
}
export default {
  components: { Pagination, CatalogTree, Detail, Upload },
  data() {
    return {
      caseList: [],
      multipleSelection: [],
      verOptions: [],
      catalogOptions: [],
      submitType: 0, // 0新增 1编辑
      caseInfo: {},
      steps: [],
      listLoading: false,
      page: 1,
      limit: 10,
      total: 0,
      q: '',
      status: null,
      level: null,
      catalogId: null,
      isChange: false,
      curCaselibName: '',
      curCaselibId: null,
      caselibOptions: [],
      caseDrawerTitle: '新增用例',
      caseDrawerShow: false,
      importDrawerShow: true
    }
  },
  computed: {
    caselibId() {
      return Number(this.$route.query.caselibId)
    },
    levelOptions() {
      return this.$store.state.user.dicts.common_case_level || []
    },
    statusOptions() {
      return this.$store.state.user.dicts.common_case_status.map(option => ({
        ...option,
        value: parseInt(option.value, 10)
      })) || []
    }
  },
  watch: {
    '$route.query.caselibId': function(newVal) {
      // 当caselibId查询参数变化时，更新curCaselibId的值
      this.curCaselibId = Number(newVal)
      this.setCurCaselibName()
    }
  },
  created() {
    this.getCaselibOptions()
    this.fetchData()
  },
  methods: {
    setCurCaselibName() {
      this.curCaselibId = this.caselibId
      const selectedOption = this.caselibOptions.find(option => option.id === this.curCaselibId)
      this.curCaselibName = selectedOption.name
    },
    fetchData() {
      this.listLoading = true
      const params = {
        page: this.page,
        limit: this.limit,
        title: this.q,
        caselib_id: this.$route.query.caselibId,
        status: this.status,
        level: this.level
      }
      const data = {
        catalog_ids: this.catalogIds
      }
      apiTestcase.getTestcaseList(data, params).then(response => {
        this.caseList = response.data
        this.total = response.count
      })
      this.listLoading = false
    },
    changeCatalogId(catalogIds) {
      this.catalogIds = catalogIds
      this.fetchData()
    },
    getCaselibOptions() {
      apiCaselib.getCaselibOptions().then(response => {
        this.caselibOptions = response.data
        this.setCurCaselibName()
      })
    },
    getVersionOpts() {
      apiVer.getVersionList().then(response => {
        this.verOptions = response.data
      })
    },
    changeSelect() {
      this.isChange = !this.isChange
    },
    selectChange(value) {
      this.isChange = false
      this.$router.push({
        path: '/functional/casemanage',
        query: {
          caselibId: value
        }
      })
      this.fetchData()
    },
    receiveCatalogList(value) {
      this.catalogOptions = value
    },
    addCase() {
      this.submitType = 0
      this.caseDrawerShow = true
      this.caseInfo = Object.assign({}, defaultCaseInfo)
      this.steps = []
    },
    editCase(row) {
      this.submitType = 1
      this.caseDrawerShow = true
      this.caseDrawerTitle = '编辑用例'
      this.getTestcaseInfo({ testcaseId: row.id, versionId: row.version_id })
    },
    closeDrawer(refresh) {
      this.caseDrawerShow = false
      if (refresh) {
        this.fetchData()
      }
    },
    getTestcaseInfo(obj) {
      apiTestcase.getTestcaseInfo(obj.testcaseId, { version_id: obj.versionId }).then(response => {
        this.caseInfo = response.data
        this.steps = response.data.steps
      })
    },
    deleteCase(row) {
      this.$confirm('确定要删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        lockScroll: false,
        type: 'warning'
      }).then(async() => {
        const data = [row.id]
        await apiTestcase.deleteTestcase(data).then(async response => {
          this.$message.success(response.message || '删除成功')
          await this.fetchData()
        })
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleBatchDelete() {
      this.$confirm('确定要删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        lockScroll: false,
        type: 'warning'
      }).then(async() => {
        const selectIds = []
        this.multipleSelection.forEach(row => {
          selectIds.push(row.id)
        })
        apiTestcase.deleteTestcase(selectIds).then(response => {
          this.$message.success(response.message || '删除成功')
          this.fetchData()
        })
      })
    },
    handleImport() {
      this.importDrawerShow = true
    },
    async downTemplateFile() {
      try {
        // 发送 GET 请求下载模板文件
        const response = await fetch(process.env.VUE_APP_BASE_API + '/functional/testcase/import/template', {
          method: 'GET',
          responseType: 'blob' // 告诉 fetch 返回的数据类型是 Blob
        })

        if (!response.ok) {
          throw new Error('下载模板文件失败')
        }

        // 获取文件名
        const disposition = response.headers.get('Content-Disposition')
        let filename = '测试用例导入模板.xlsx' // 默认文件名，如果后端没有正确设置 Content-Disposition 的话

        if (disposition && disposition.indexOf('attachment') !== -1) {
          const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
          const matches = filenameRegex.exec(disposition)
          if (matches != null && matches[1]) {
            filename = matches[1].replace(/['"]/g, '')
          }
        }

        // 创建 Blob 对象并下载
        const blob = await response.blob()
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.style.display = 'none'
        a.href = url
        a.download = filename // 下载的文件名
        document.body.appendChild(a)
        a.click()
        window.URL.revokeObjectURL(url)
      } catch (error) {
        console.error('下载模板文件失败', error)
        // 处理错误，例如显示错误信息给用户
        this.$message.error('下载模板失败！')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.card-head {
  display: flex;
  align-items: center;
  margin-bottom: 10px;

  .card-head__text {
    font-size: 14px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    width: 80%;
    min-width: 0;

    .text-content {
      color: #606266;
      margin-left: 10px;
    }
  }

}

.el-card {
  border: 0;
}

// 取消卡片的padding
::v-deep .el-card__body {
  padding: 0;
}

.custom-dropdown-item {
  height: 35px; /* 设置高度 */
  line-height: 36px; /* 设置行高以垂直居中内容 */
  padding: 0 15px; /* 根据需要设置内边距 */
  /* 你可以添加其他需要的样式，如边框、背景色等 */
}

</style>
